package com.gsafety.wellsfort.config;


import com.gsafety.wellsfort.common.util.ApiResponse;
import com.gsafety.wellsfort.common.util.ResultCode;
import com.gsafety.wellsfort.exception.TokenException;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理类
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ApiResponse handleException(Exception e) {
        log.info("e={}", e);
        if (e instanceof TokenException) {
            //token异常,返回状态码单独处理
            TokenException tokenException = (TokenException) e;
            return ApiResponse.error(tokenException.getResultCode());
        }
        if (e instanceof SignatureException || e instanceof ExpiredJwtException) {
            return ApiResponse.error(ResultCode.INVALID_TOKEN);
        }
        return ApiResponse.error(ResultCode.ERROR);
    }
}